<?php
namespace app\massage\controller;
use app\AdminRest;
use app\BaseController;
use app\massage\info\PermissionMassage;
use app\massage\model\ActionLog;
use app\massage\model\City;
use app\massage\model\Coach;
use app\massage\model\Config;
use app\massage\model\Order;
use app\massage\model\ShortCodeConfig;
use longbingcore\wxcore\Excel;
use think\App;

use app\massage\model\CoachTimeList;
use app\massage\model\Comment;
use app\massage\model\ExpectationCityList;


use app\massage\model\User;


use think\facade\Cookie;
use think\facade\Db;
use think\facade\Lang;
use think\Response;

class Admin extends BaseController
{


    protected $model;

    protected $config_model;

    protected $uniacid;
    protected $_uniacid;



    public function __construct(App $app) {

        parent::__construct($app);

        $this->model = new \app\massage\model\Admin();

        $this->uniacid = 666;

        $this->_uniacid = 666;

    }


    /**
     * @author chenniang
     * @DataTime: 2023-05-19 16:36
     * @功能说明:获取版权信息
     */
    public function getW7TmpV2(){

        $copyright = getConfigSetting(666,'copyright');

        if(!empty($copyright)){

            $arr['w7tmp']['footerleft'] = "<div> $copyright </div>";
        }else{

            $arr['w7tmp'] = 1;
        }

        return $this->success($arr);

    }


    /**
     * @author chenniang
     * @DataTime: 2023-05-24 11:41
     * @功能说明:是否需要手机号验证
     */
    public function authPhone(){

        $phone = getConfigSetting(666,'login_phone_auth');

        $auth = $phone==1&&empty(cookie('getAuthPhone'))?1:0;

        return $this->success($auth);
    }


    /**
     * @author chenniang
     * @DataTime: 2023-05-24 13:51
     * @功能说明:发送短信验证码
     */
    public function sendAuthCode(){

        $input = json_decode( $this->request->getInput(), true );

        $dis = [

            'status'  => 1,

            'username'=> $input['username'],

            'passwd'  => checkPass($input['passwd'])
        ];

        $data = $this->model->dataInfo($dis);

        if(empty($data)){

            return $this->error('密码错误', 400);
        }
        //超级管理员需要获取平台授权手机号
        if($data['is_admin']==1){

            $phone = getConfigSetting($data['uniacid'],'login_auth_phone');

        }else{

            $phone = $data['phone'];
        }

        if(empty($phone)){

            return $this->error('未获取到授权手机号，请联系开发平台', 400);
        }

        $config_model = new ShortCodeConfig();

        $res = $config_model->loginShortConfig($phone,$data['uniacid']);

        if(!empty($res['Message'])&&$res['Message']=='OK'){

            return $this->success($phone);

        }else{

            return $this->error($res['Message']);

        }

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-11 13:53
     * @功能说明:登陆
     */
    public function login(){

        initLogin();

        $input = json_decode( $this->request->getInput(), true );

        $codeText = cookie('codeText');
        //判断是否需要短信验证
        $phone_auth = getConfigSetting(666,'login_phone_auth');

        $auth = $phone_auth==1&&empty(cookie('getAuthPhone'))?1:0;

        if($auth==0&&$codeText!=$input['codeText']){

            return $this->error('验证码错误');
        }

        $ip = getIP();

        $key = $ip.'errss_numsss';

        $err_num = getCache($key,66661);

        $err_num = !empty($err_num)?$err_num:0;

        if($err_num>=5){

            return $this->error('密码错误超过5次，请2小时后再试', 400);

        }

        $err_num+=1;

        setCache($key,$err_num,7200,66661);

        $dis = [

            'status'  => 1,

            'username'=> $input['username'],

            'passwd'  => checkPass($input['passwd'])
        ];

        $data = $this->model->dataInfo($dis);

        $login_num = 5 - $err_num;

        if(empty($data)){

            if($login_num<=0){

                return $this->error('密码错误超过5次，请2小时后再试', 400);

            }else{

                return $this->error('账号密码错误，你还剩'.$login_num.'次机会', 400);
            }
        }
        //需要验证码
        if($auth==1){
            //判断是否是超级管理员账号
            $short_phone = $data['is_admin']==1?getConfigSetting(666,'login_auth_phone'):$data['phone'];

            $short_code  = getCache($short_phone.'login',$data['uniacid']);

            if(empty($input['short_code'])||$short_code!=$input['short_code']){

                return $this->error('短信验证码错误', 400);
            }

            \cookie('getAuthPhone',1,86400*30);

            setCache($short_phone.'login','',99,$data['uniacid']);
        }

        setCache($key,0,7200,66661);

        $result['user'] = $data;

        $result['token'] = uuid();

        if (empty($result['token'])) {

            return $this->error('系统错误', 400);
        }
        //添加缓存数据
        setUserForToken($result['token'], $data);

        $this->addActionLog($data['id']);

        return $this->success($result);
    }


    /**
     * @param $user_id
     * @功能说明:
     * @author chenniang
     * @DataTime: 2023-03-29 10:03
     */
    public function addActionLog($user_id){

        $insert = [

            'uniacid'     => 666,

            'user_id'     => $user_id,

            'obj_id'      => 0,

            'ip'          => getIP(),

            'model'       => 'Admin',

            'method'      => 'POST',

            'table'       => 'shequshop_school_admin',

            'code_action' => 'login',

            'action_type' => '',

            'action'      => 'login',

        ];

        $log_model = new ActionLog();

        $log_model->dataAdd($insert);

        return true;
    }



    public function success ( $data, $code = 200 )
    {
        $result[ 'data' ] = $data;
        $result[ 'code' ] = $code;
        $result[ 'sign' ] = null;
        //简单的签名
        if ( !empty( $this->_token ) ) $result[ 'sign' ] = createSimpleSign( $this->_token, is_string( $data ) ? $data : json_encode( $data ) );

        return $this->response( $result, 'json', $code  );
    }

    //返回错误数据
    public function error ( $msg, $code = 400 )
    {
        $result[ 'error' ] = Lang::get($msg);
        $result[ 'code' ]  = $code;
        return $this->response( $result, 'json', 200 );
    }

    /**
     * 输出返回数据
     * @access protected
     * @param mixed $data 要返回的数据
     * @param String $type 返回类型 JSON XML
     * @param integer $code HTTP状态码
     * @return Response
     */
    protected function response ( $data, $type = 'json', $code = 200 )
    {
        return Response::create( $data, $type )->code( $code );
    }


    /**
     * @author chenniang
     * @DataTime: 2022-08-11 11:33
     * @功能说明:
     */
    public function getConfig(){

        $config_model = new Config();

        $config = $config_model->dataInfo(['uniacid'=>666]);

        $data['record_type'] = $config['record_type'];

        $data['record_no'] = $config['record_no'];

        return $this->success($data);

    }




    public function excel(){

        $a = Db::name('auth_domain_name')->where(['goods_id'=>19])->column('url');

        $data = Db::name('admin_violation')->where(['goods_id'=>19])->where('url','not in',$a)->group('url')->select()->toArray();

        $name = '按摩盗版';

        $header=[
            '域名',
            '最后登录时间',
        ];

        foreach ($data as $v){

            $info   = array();

            $info[] = $v['url'];

            $info[] = date('Y-m-d H:i:s',$v['last_time']);

            if(!strstr($v['url'],':')&&!$this->checkipaddres($v['url'])){

                $new_data[] = $info;
            }

        }

        $excel = new Excel();

        $excel->excelExport($name,$header,$new_data);

        return $this->success($data);

    }




    public function checkipaddres ($ipaddres) {

        $preg="/\A((([0-9]?[0-9])|(1[0-9]{2})|(2[0-4][0-9])|(25[0-5]))\.){3}(([0-9]?[0-9])|(1[0-9]{2})|(2[0-4][0-9])|(25[0-5]))\Z/";

        if(preg_match($preg,$ipaddres))return true;

        return false;

    }



    /**
     * @author chenniang
     * @DataTime: 2023-06-20 13:58
     * @功能说明:获取技师地图数据
     */
    public function getMapCoach(){

        $input = $this->_param;

        $dis[] = ['uniacid','=',666];

        $dis[] = ['status','=',2];

        if(!empty($input['city_id'])){

            $dis[] = ['city_id','=',$input['city_id']];

        }

        $coach_model = new Coach();

        $data = $coach_model->where($dis)->field('id as coach_id,lng,lat,coach_name,work_img')->select()->toArray();

        return $this->success($data);
    }


    /**
     * @author chenniang
     * @DataTime: 2023-06-26 18:06
     * @功能说明:城市下拉框
     */
    public function citySelect(){

        $input = $this->_param;

        $city_model = new City();

        $dis[] = ['uniacid','=',666];

        $dis[] = ['status','=',1];

        $mapor = [

            'city_type' => 1,

            'is_city'   => 1

        ];

        $data = $city_model->where($dis)->where(function ($query) use ($mapor){
            $query->whereOr($mapor);
        })->field(['id,title,lat,lng'])->order('id desc')->select()->toArray();

        return $this->success($data);
    }


    /**
     * @author chenniang
     * @DataTime: 2023-06-26 18:06
     * @功能说明:技师详情
     */
    public function coachInfo(){

        $input = $this->_param;

        $dis = [

            'id' => $input['id']
        ];

        $coach_model = new Coach();

        $data = $coach_model->where($dis)->withoutField('id_card,id_code,mobile,service_price')->find()->toArray();

        $config_model = new Config();

        $config= $config_model->dataInfo(['uniacid'=>$this->uniacid]);

        $data['text_type'] = $coach_model->getCoachWorkStatus($input['id'],$this->uniacid);

        $data['near_time'] = $coach_model->getCoachEarliestTime($input['id'],$config);

        $data['order_num'] += $data['total_order_num'];

        return $this->success($data);

    }




    /**
     * @author chenniang
     * @DataTime: 2022-05-25 15:16
     * @功能说明:销售额订单数据
     */
    public function orderData(){

        $input = $this->_param;

        $dis[] = ['uniacid','=',$this->_uniacid];

        $dis[] = ['pay_time','>',0];

        $dis[] = ['pay_type','>',1];

        $order_model = new Order();
        //全年
        if($input['day']==4){

            $start = strtotime(date('Y-01'));

            $i = 0;

            while ($i<12){

                $arr[$i]['month'] = $i+1;

                $arr[$i]['time'] = $start;

                $time_text = date('Y-m',$start);

                $arr[$i]['time_text'] = $time_text;
                //商城收益
                $shop_price = $order_model->where($dis)->whereMonth('create_time',$time_text)->sum('true_service_price');
                //录入订单
                $arr[$i]['shop_price']  = round($shop_price,2);

                $i++;

                $start = strtotime("$time_text +1 month");
            }

        }else{
            //自定义
            if($input['day']==5) {

                $start = $input['start_time'];

                $end   = $input['end_time'];

            }else{

                if($input['day']==1){

                    $time = 1;

                }elseif ($input['day']==2){

                    $time = 7;

                }else{

                    $time = 30;

                }

                $end   = strtotime(date('Y-m-d',time()));

                $start = $end - ($time-1)*86400;

            }

            $i = 0;

            while ($start<=$end){

                $arr[$i]['time'] = $start;

                $time_text = date('Y-m-d',$start);

                $arr[$i]['time_text'] = $time_text;

                $shop_price = $order_model->where($dis)->whereDay('create_time',$time_text)->sum('true_service_price');

                $arr[$i]['shop_price']  = round($shop_price,2);

                $start += 86400;

                $i++;
            }

        }

        return $this->success($arr);
    }


    /**
     * @author chenniang
     * @DataTime: 2023-08-04 09:54
     * @功能说明:数据大屏
     */
    public function dataScreen(){

        $order_model = new Order();

        $dis = [

            'uniacid' => $this->_uniacid,

            'status'  => 2
        ];

        $where = [];

        $coach_model = new Coach();
        //技师总数
        $data['coach']['total_count'] = $coach_model->where($dis)->where($where)->count();
        //待认证
        $data['coach']['notcertified_count'] = $coach_model->where($dis)->where($where)->where('auth_status','<>',2)->count();

        $work = CoachTimeList::getWorkOrResetCoach($this->_uniacid);

        $reset = CoachTimeList::getWorkOrResetCoach($this->_uniacid,2);

        $working_coach = $coach_model->getWorkingCoach($this->_uniacid);
        //休息技师
        $data['coach']['rest_count'] = $coach_model->where($dis)->where($where)->where('id','in',$reset)->count();
        //可服务
        $data['coach']['app_count']  = $coach_model->where($dis)->where($where)->where('id','in',$working_coach)->count();
        //在线
        $data['coach']['work_count'] = $coach_model->where($dis)->where($where)->where('id','in',$work)->count();

        $dis = [];

        $dis[] = ['pay_type','>',1];

        $dis[] = ['uniacid','=',$this->_uniacid];
        //订单信息
        $data['order']['today_order_cash']  = $order_model->where($dis)->whereTime('create_time','today')->sum('true_service_price');

        $data['order']['today_order_cash']  = round($data['order']['today_order_cash'],2);

        $data['order']['today_order_count'] = $order_model->where($dis)->whereTime('create_time','today')->count();

        $data['order']['total_order_cash']  = $order_model->where($dis)->sum('true_service_price');

        $data['order']['total_order_cash']  = round($data['order']['total_order_cash'],2);

        $data['order']['total_order_count'] = $order_model->where($dis)->count();
        //技师排行
        $dis = [];

        $dis[] = ['b.pay_type','>',1];

        $dis[] = ['a.status','=',2];

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $coach_data = $coach_model->alias('a')
            ->join('massage_service_order_list b','a.id = b.coach_id')
            ->where($dis)
            ->field('a.coach_name,a.admin_id,sum(b.true_service_price) as order_price')
            ->group('a.id')
            ->order('order_price desc,a.id desc')
            ->limit(10)
            ->select()
            ->toArray();
        if(!empty($coach_data)){

            $admin_model = new \app\massage\model\Admin();

            foreach ($coach_data as &$v){

                $v['order_price']= round($v['order_price'],2);

                $v['admin_name'] = $admin_model->where(['id'=>$v['admin_id'],'status'=>1])->value('agent_name');

            }
        }

        $data['coach_top'] = $coach_data;
        //最新订单
        $dis = [];

        $dis[] = ['pay_type','=',2];

        $dis[] = ['uniacid','=',$this->_uniacid];

        $data['new_order'] = $order_model->where($dis)->order('id desc')->limit(10)->select()->toArray();
        //城市
        $dis = [

            'uniacid' => $this->_uniacid,

            'status'  => 1,

            'city_type'=> 1
        ];

        $city_model = new City();

        $data['city_list'] = $city_model->where($dis)->field('city,lng,lat')->select()->toArray();

        $end = strtotime(date('Y-m-d',time()))+86400;

        $start = $end-86400*29;

        $user_model = new User();

        $dis = [];

        $dis[] = ['uniacid','=',$this->_uniacid];

        $dis[] = ['status','=',1];

        $i = 0;

        $arr = [];

        while ($start<=$end){

            $arr[$i]['time'] = $start;

            $time_text = date('Y-m-d',$start);

            $arr[$i]['time_text'] = $time_text;

            $user_count = $user_model->where($dis)->whereDay('create_time',$time_text)->count();

            $order_user_id = $order_model->where('pay_time','>',0)->whereDay('create_time',$time_text)->column('user_id');

            $order_user_count = $user_model->where($dis)->where('id','in',$order_user_id)->whereDay('create_time',$time_text)->count();
            //新用户
            $arr[$i]['new_user_count']  = round($user_count,2);
            //下单用户
            $arr[$i]['order_user_count'] = round($order_user_count,2);

            $start += 86400;

            $i++;
        }
        $data['user_data'] = $arr;

        return $this->success($data);
    }








}
